package com.amat0urheu.service.cloudService.impl;

import com.amat0urheu.dao.*;
import com.amat0urheu.pojo.CloudPojo.OpenStack;
import com.amat0urheu.pojo.CloudPojo.VMservice;
import com.amat0urheu.pojo.ReturnRes;
import com.amat0urheu.service.cloudService.VMService;
import com.amat0urheu.utils.CloudUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Random;

@Service
public class VMServiceImpl implements VMService {
    @Autowired
    CloudMapper cloudMapper;
    @Autowired
    VmMapper vmMapper;
    @Autowired
    SceneMapper sceneMapper;
    @Autowired
    NetWrokMapper netWorkMapper;
    @Autowired
    ImageMapper imageMapper;
    @Autowired
    ExperimentsMapper experimentsMapper;
    @Autowired
    RaceMapper raceMapper;
    @Override
    public ReturnRes getVMservices( ) {
        long startTime = System.currentTimeMillis();
        List<VMservice> vmlist = CloudUtils.getVMservices(cloudMapper.getAllOpenstack());
        long endTime = System.currentTimeMillis();
        double elapsedTimeInSeconds = (endTime - startTime) / 1000.0;
        System.out.println("消耗时间: "+elapsedTimeInSeconds+"秒");
        for (VMservice vm : vmlist){
            //查询数据库中是否存在
                vmMapper.updateVmyVMId(vm);


        }
        return new ReturnRes(true,vmlist);
    }

    @Override
    public ReturnRes createVMservices(String name, Integer num,Integer time) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date()); // 设置当前时间
        calendar.add(Calendar.HOUR_OF_DAY, time); // 添加时间点
        Date deadTime = calendar.getTime(); // 获取修改后的时间
        
        System.err.println("开始创建"+name);
        Integer sId= sceneMapper.getExperimentToScene(  experimentsMapper.getExperimentId(name));

        Integer clientId=sceneMapper.getclientBySid(sId);//获得需要创建的客户的Id
        List<Integer> victimIds=sceneMapper.getVictimIdsBysId(sId);//获得需要创建的靶机的Id

        for (int i=0;i<num;i++){
            //名称随机数
            Integer RandomNum= new Random().nextInt(10000);
            //每次寻找实例数量最少的openstack服务器 进行创建
            OpenStack  openstack= cloudMapper.getMinVmNumofOpenstack();
            String network=netWorkMapper.findRanNetWork(openstack.getOpenstackIP());//随机网络,但是一个实验的几台服务器需要在统一个网络下
            String  flavor=imageMapper.getFlavorofVM(clientId);
            String client=  imageMapper.getImageName(clientId);


            VMservice clientVm = CloudUtils.createVMservices(name, openstack, client, RandomNum, network, flavor);//创建客户机器
            clientVm.setType(client);
            clientVm.setOpenstackIP(openstack.getOpenstackIP());
            clientVm.setDeadTime(deadTime);
            experimentsMapper.insertEmxperimentVm(clientVm);
            cloudMapper.updatecountVmOfOpenstack(openstack.getOpenstackIP());


            //根据 victimId 进行创建
            for (Integer victimId:victimIds) {
                flavor=imageMapper.getFlavorofVM(victimId);
                //获得镜像的名称
                String victim=  imageMapper.getImageName(victimId);
                //创建靶机


                VMservice victimVm = CloudUtils.createVMservices(name, openstack, victim, RandomNum, network, flavor);
                victimVm.setType(victim);
                victimVm.setOpenstackIP(openstack.getOpenstackIP());

                victimVm.setDeadTime(deadTime);
                //存入数据库中
                System.out.println("即将存入数据库的数据：  "+victimVm);
                experimentsMapper.insertEmxperimentVm(victimVm);

                cloudMapper.updatecountVmOfOpenstack(openstack.getOpenstackIP());
            }
        }
        System.out.println("结束创建");
        return new ReturnRes(true, "创建成功");
    }

    @Override
    public ReturnRes stopVm(String vmID,String action) {
        String openstackIP=vmMapper.getOpenstackIPofVm(vmID);
        if(action.equals("stop")){


            int count=vmMapper.deleteVm(vmID);
            if(count!=0){

                boolean b = CloudUtils.deleteVm(cloudMapper.getOpenstackByopenstackIP(openstackIP), vmID);
                //释放资源后,删掉对应的flag
                raceMapper.deleteFlags(vmID);
                if(b){
                    System.out.println("实例释放成功");

                }else {
                    System.out.println("服务器中的实例可能不存在");
                }

                return new ReturnRes(true, "实例资源释放成功");
            }
        }

        return new ReturnRes(false, "实例资源释放失败");
    }

    @Override
    public ReturnRes resetVmServer(String vmID) {
        //获得openstackIP

        OpenStack  openstack= cloudMapper.getOpenstackByopenstackIP(vmMapper.getOpenstackIPofVm(vmID));

        VMservice vMservice=vmMapper.getRaceVms(vmID);
        CloudUtils.resetVmServer(vMservice,openstack);
        return new ReturnRes(true, "重置成功");
    }

    @Override
    public ReturnRes updatevmOfUser(String vmName ,String name) {
            int count =vmMapper.updatevmOfUser(vmName,name);

            if(count>=0){
                return new ReturnRes(true, "连接成功");
            }
        return null;

    }
}
